<?php

namespace App\Http\Middleware;

use App\Baby;
use App\WechatUser;
use Closure;
use Illuminate\Support\Facades\DB;

class UserBabies
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    // 获取已经选宝宝和课程的信息
    public function handle($request, Closure $next)
    {
        $user = session('wechat.oauth_user');
        if(    empty(session('yuebao.wechat_user_id'))
            || empty(session('yuebao.baby_id'))
            || empty(session('yuebao.baby_sub_courses'))  ){

            $open_id = $user->getOriginal()['openid'];
            $nick_name = $user->nickname;
            $wechat_user = WechatUser::firstOrCreate(['open_id' => $open_id], ['nick_name' => $nick_name]);
            $baby = $wechat_user->babies()->first();
            if(empty($baby)){
                return redirect('/wx/regist');
            }
            session(['yuebao.wechat_user_id'=>$wechat_user->id,'yuebao.baby_id'=> $baby->id]);
        }
        $baby_id = session('yuebao.baby_id');
        $baby = Baby::find($baby_id);
        $sub_course_times =  $baby->subscribes()->where('course_time', '>', date('Y-m-d H:i:s', time()))->pluck('course_time_id')->all();

        session(['yuebao.baby_sub_course_times' => $sub_course_times]);
        return $next($request);
    }
}
